package com.paradise.ytj.fragment;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paradise.api.FacephonePreferences;
import com.paradise.ytj.R;
import com.paradise.ytj.activity.VideoActivity;
import com.paradise.ytj.bean.HangupEvent;
import com.paradise.ytj.bean.MenuVideoEvent;
import com.paradise.ytj.bean.VideoBackEvent;
import com.paradise.ytj.bean.VisiableEvent;
import com.paradise.api.FaceCall;
import com.paradise.api.FacePhone;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCore;
import org.linphone.mediastream.video.display.GL2JNIView;

/**
 * Created by Administrator on 2017/8/24 0024.
 */

public class VideoFragment extends Fragment implements View.OnClickListener, View.OnFocusChangeListener, View.OnTouchListener {

    private GL2JNIView gvRemote;
    private SurfaceView svLocation;
    private RadioButton ivMute;
    private RadioButton ivFinish;
    private LinearLayout llMenu;
    private TextView etFragmentCallMenu;
    private int currentMenuTime = 0;
    private boolean isVisiable = true;
    private View inflate;
    private LinearLayout llInder;
    private FrameLayout flVideo;
    private boolean mPlayDtmf = true;
    private boolean mIsDtmfStarted = false;
    private boolean is = true;
    private int layout_bumber = 0;
    private boolean isTwo = true;
    private boolean isFlag = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    llInder.setVisibility(View.GONE);
                    if (show) {
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
                        params.setMargins(0, 0, 0, 0);
                        svLocation.setLayoutParams(params);
                    }
                    ivParam.requestFocus();
                    break;
                case 1:
                    llMenu.setVisibility(View.GONE);
                    if (show) {
                        RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
                        params1.setMargins(0, 0, 0, 0);
                        svLocation.setLayoutParams(params1);
                    }
                    ivParam.requestFocus();
                    break;
                case 2:
                    break;
                case 3:
                    LinphoneCall currentCall = FacePhone.instance().getmLc().getCurrentCall();
                    if (currentCall != null) {
                        int quality = (int) currentCall.getAverageQuality();
                        if (quality == 0) {
                            ivParam.setImageResource(R.drawable.iv_info_1);
                        } else if (quality == 1 || quality == 2) {
                            ivParam.setImageResource(R.drawable.iv_info_2);
                        } else if (quality == 3) {
                            ivParam.setImageResource(R.drawable.iv_info_3);
                        } else if (quality == 4) {
                            ivParam.setImageResource(R.drawable.iv_info_4);
                        } else if (quality == 5) {
                            ivParam.setImageResource(R.drawable.iv_info_4);
                        }
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private ImageView ivParam;
    private RadioButton ivLayout;
    private Activity context;
    private TextView ivMuteFrag;
    private View viewj;
    private RadioButton ivChange;
    private boolean show = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        context = getActivity();
        inflate = View.inflate(context, R.layout.fragment_video, null);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        commit();
        initView();
        initData();
        initMenuTime();
        initListener();
        super.onActivityCreated(savedInstanceState);
    }

    private void commit() {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        StateVideoFragment fragment = new StateVideoFragment();
        transaction.add(R.id.fl_state_video, fragment);
        transaction.commit();
    }

    private void initView() {
        gvRemote = (GL2JNIView) inflate.findViewById(R.id.gv);
        svLocation = (SurfaceView) inflate.findViewById(R.id.sg);
        flVideo = (FrameLayout) inflate.findViewById(R.id.fl_state_video);
        ivChange = (RadioButton) inflate.findViewById(R.id.rb_change);
        ivLayout = (RadioButton) inflate.findViewById(R.id.rb_layout);
        ivLayout.setTag('2');
        ivMute = (RadioButton) inflate.findViewById(R.id.rb_mute);
        ivFinish = (RadioButton) inflate.findViewById(R.id.rb_finish);
        ivParam = (ImageView) inflate.findViewById(R.id.rb_param);
        ivMuteFrag = (TextView) inflate.findViewById(R.id.iv_mute_frag);

        llMenu = (LinearLayout) inflate.findViewById(R.id.ll_menu);
        llInder = (LinearLayout) inflate.findViewById(R.id.rg_group);
        etFragmentCallMenu = (TextView) inflate.findViewById(R.id.et_fragment_call_menu);

        View view0 = inflate.findViewById(R.id.tv_fragment_call_menu_0);
        view0.setTag('0');
        view0.setOnClickListener(this);
        view0.setOnTouchListener(this);
        view0.setOnFocusChangeListener(this);

        View view1 = inflate.findViewById(R.id.tv_fragment_call_menu_1);
        view1.setTag('1');
        view1.setOnClickListener(this);
        view1.setOnTouchListener(this);
        view1.setOnFocusChangeListener(this);

        View view2 = inflate.findViewById(R.id.tv_fragment_call_menu_2);
        view2.setTag('2');
        view2.setOnClickListener(this);
        view2.setOnTouchListener(this);
        view2.setOnFocusChangeListener(this);

        View view3 = inflate.findViewById(R.id.tv_fragment_call_menu_3);
        view3.setTag('3');
        view3.setOnClickListener(this);
        view3.setOnTouchListener(this);
        view3.setOnFocusChangeListener(this);

        View view4 = inflate.findViewById(R.id.tv_fragment_call_menu_4);
        view4.setTag('4');
        view4.setOnClickListener(this);
        view4.setOnTouchListener(this);
        view4.setOnFocusChangeListener(this);

        View view5 = inflate.findViewById(R.id.tv_fragment_call_menu_5);
        view5.setTag('5');
        view5.setOnClickListener(this);
        view5.setOnTouchListener(this);
        view5.setOnFocusChangeListener(this);

        View view6 = inflate.findViewById(R.id.tv_fragment_call_menu_6);
        view6.setTag('6');
        view6.setOnClickListener(this);
        view6.setOnTouchListener(this);
        view6.setOnFocusChangeListener(this);

        View view7 = inflate.findViewById(R.id.tv_fragment_call_menu_7);
        view7.setTag('7');
        view7.setOnClickListener(this);
        view7.setOnTouchListener(this);
        view7.setOnFocusChangeListener(this);

        View view8 = inflate.findViewById(R.id.tv_fragment_call_menu_8);
        view8.setTag('8');
        view8.setOnClickListener(this);
        view8.setOnTouchListener(this);
        view8.setOnFocusChangeListener(this);

        View view9 = inflate.findViewById(R.id.tv_fragment_call_menu_9);
        view9.setTag('9');
        view9.setOnClickListener(this);
        view9.setOnTouchListener(this);
        view9.setOnFocusChangeListener(this);

        View viewx = inflate.findViewById(R.id.tv_fragment_call_menu_x);
        viewx.setTag('*');
        viewx.setOnClickListener(this);
        viewx.setOnTouchListener(this);
        viewx.setOnFocusChangeListener(this);

        viewj = inflate.findViewById(R.id.tv_fragment_call_menu_j);
        viewj.setTag('#');
        viewj.setOnClickListener(this);
        viewj.setOnTouchListener(this);
        viewj.setOnFocusChangeListener(this);


    }

    private void initData() {
        ivMute.requestFocus();
        FaceCall.instance().displayVideo(gvRemote, svLocation, null);
        //获取系统最大音量
        isVisiable = true;
        Bundle bundle = getArguments();
        String phone = bundle.getString("phone");
        ScaleAnimation animation = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(1500);
        animation.setRepeatCount(1000);
        animation.setRepeatMode(Animation.REVERSE);
        if (phone != null) {
            String s = phone.substring(0, 2);
            String substring = phone.substring(0, 1);
            if (s.equals("79") || substring.equals("9")) {
                llMenu.setVisibility(View.VISIBLE);
                viewj.requestFocus();
                if (!FaceCall.instance().isMuted()) {
                    FaceCall.instance().micMuted();
                }
                VideoActivity.isFirstBack = true;
            } else {
                llMenu.setVisibility(View.GONE);
                if (FaceCall.instance().isMuted()) {
                    FaceCall.instance().isMuted();
                }
            }
        }
        if (FaceCall.instance().isMuted()) {
            Drawable drawable = context.getResources().getDrawable(R.drawable.call_mute_open_selector);
            ivMute.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            ivMute.setText(context.getString(R.string.mute));
            ivMuteFrag.setVisibility(View.VISIBLE);
        } else {
            Drawable drawable = context.getResources().getDrawable(R.drawable.call_mute_close_selector);
            ivMute.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            ivMute.setText(context.getString(R.string.sonic));
            ivMuteFrag.setVisibility(View.INVISIBLE);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (is) {
                    SystemClock.sleep(1500);
                    handler.sendEmptyMessage(3);
                }

            }
        }).start();

    }

    /**
     * 初始化pager時間控制器
     */
    private void initMenuTime() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isVisiable) {
                    try {
                        Thread.sleep(1000);
                        currentMenuTime++;
                        if (currentMenuTime >= 16) {
                            if (llInder.getVisibility() == View.VISIBLE) {
                                handler.sendEmptyMessage(0);
                            }
                            if (llMenu.getVisibility() == View.VISIBLE) {
                                handler.sendEmptyMessage(1);
                            }
                            if (flVideo.getVisibility() == View.VISIBLE) {
                                handler.sendEmptyMessage(2);
                            }
                            currentMenuTime = 0;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void initListener() {
        gvRemote.setOnClickListener(this);
        ivMute.setOnClickListener(this);
        ivFinish.setOnClickListener(this);
        ivParam.setOnClickListener(this);
        ivLayout.setOnClickListener(this);
        ivLayout.setOnTouchListener(this);
        ivChange.setOnClickListener(this);

        ivMute.setOnFocusChangeListener(this);
        ivFinish.setOnFocusChangeListener(this);
        ivChange.setOnFocusChangeListener(this);
        ivParam.setOnFocusChangeListener(this);
        ivLayout.setOnFocusChangeListener(this);

        EventBus.getDefault().register(this);

        llInder.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                llInder.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
                params.setMargins(0, 0, 0, llInder.getHeight());
                svLocation.setLayoutParams(params);
            }
        });

    }

    @Override
    public void onClick(View view) {
        currentMenuTime = 0;
        if (llInder.getVisibility() == View.GONE) {
            llInder.setVisibility(View.VISIBLE);
        }
        switch (view.getId()) {

            case R.id.tv_fragment_call_menu_j:
                llMenu.setVisibility(View.GONE);
                ivMute.requestFocus();
                break;

            case R.id.rb_mute:
                ivMute.requestFocus();
                //静音
                FaceCall.instance().micMuted();
                if (FaceCall.instance().isMuted()) {
                    Drawable drawable = context.getResources().getDrawable(R.drawable.call_mute_open_selector);
                    ivMute.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                    ivMute.setText(context.getString(R.string.mute));

                    ScaleAnimation animation = new ScaleAnimation(0f,
                            1f,
                            1f,
                            1f,
                            Animation.RELATIVE_TO_SELF, 1f,
                            Animation.RELATIVE_TO_SELF, 0f);
                    animation.setDuration(200);
                    animation.setFillAfter(true);
                    ivMuteFrag.startAnimation(animation);
                } else {
                    Drawable drawable = context.getResources().getDrawable(R.drawable.call_mute_close_selector);
                    ivMute.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                    ivMute.setText(context.getString(R.string.sonic));
                    ScaleAnimation animation = new ScaleAnimation(1f,
                            0f,
                            1f,
                            1f,
                            Animation.RELATIVE_TO_SELF, 1f,
                            Animation.RELATIVE_TO_SELF, 0f);
                    animation.setDuration(400);
                    animation.setFillAfter(true);
                    ivMuteFrag.startAnimation(animation);
                }
                break;

            case R.id.rb_finish:
                ivFinish.requestFocus();
                //终止通话
                FaceCall.instance().terminateCurrentCall();
                HangupEvent hangupEvent = new HangupEvent();
                EventBus.getDefault().post(hangupEvent);
                break;

            case R.id.rb_change:
                if (show) {
                    RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
                    params1.setMargins(0, 0, 0, -svLocation.getHeight() - llMenu.getHeight());
                    svLocation.setLayoutParams(params1);
                    show = false;
                    Drawable drawable = context.getResources().getDrawable(R.drawable.call_camera_close_selector);
                    ivChange.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                } else {
                    RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
                    params1.setMargins(0, 0, 0, llInder.getHeight());
                    svLocation.setLayoutParams(params1);
                    show = true;
                    Drawable drawable = context.getResources().getDrawable(R.drawable.call_camera_open_selector);
                    ivChange.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                }

                break;
            case R.id.rb_param:

                if (flVideo.getVisibility() == View.INVISIBLE) {
                    flVideo.setVisibility(View.VISIBLE);
                } else {
                    flVideo.setVisibility(View.INVISIBLE);
                }
                break;

            case R.id.rb_layout:
                ++layout_bumber;
                if (layout_bumber <= 3) {
                    isTwo = true;
                } else if (layout_bumber > 3 && layout_bumber < 6) {
                    isTwo = false;

                } else if (layout_bumber == 6) {
                    isTwo = false;
                    layout_bumber = 0;
                }
                if (isTwo) {
                    ivLayout.setTag('2');
                } else {
                    ivLayout.setTag('8');
                }
                if (!isFlag) {
                    Drawable drawable = context.getResources().getDrawable(R.drawable.call_layout_2_selector);
                    ivLayout.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                } else {
                    Drawable drawable = context.getResources().getDrawable(R.drawable.call_layout_8_selector);
                    ivLayout.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                }
                isFlag = !isFlag;
                break;

            default:
                break;
        }
        if (view.getTag() != null) {
            char tag = (char) view.getTag();
            inputNumber(tag);
        }
    }

    private void inputNumber(char tag) {
        String text = etFragmentCallMenu.getText().toString();
        if (text == null) {
            text = new String(String.valueOf(tag));
        } else {
            text = text + tag;
        }
        if (text.length() > 9) {
            text = text.substring(1, text.length());
        }
        etFragmentCallMenu.setText(text);
        if (mPlayDtmf) {
            LinphoneCore lc = FacePhone.instance().getmLc();
            lc.stopDtmf();
            mIsDtmfStarted = false;
            if (lc.isIncall()) {
                lc.sendDtmf(tag);
            }
        }
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        currentMenuTime = 0;
        switch (view.getId()) {
            default:
                break;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        isVisiable = false;
        is = false;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        char tag = (char) v.getTag();
        LinphoneCore lc = FacePhone.instance().getmLc();
        if (event.getAction() == MotionEvent.ACTION_DOWN && !mIsDtmfStarted) {
            lc.playDtmf(tag, -1);
            mIsDtmfStarted = true;
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            lc.stopDtmf();
            mIsDtmfStarted = false;
        }
        return false;
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getVisiabel(VisiableEvent visiableEvent) {
        currentMenuTime = 0;
        if (visiableEvent.isMenu()) {
            if (llMenu.getVisibility() == View.GONE) {
                llMenu.setVisibility(View.VISIBLE);
            } else {
                llMenu.setVisibility(View.GONE);
            }
            if (llInder.getVisibility() == View.GONE) {
                llInder.setVisibility(View.VISIBLE);
            }
        } else {
            if (llInder.getVisibility() == View.GONE) {
                llInder.setVisibility(View.VISIBLE);
            }
        }
        if (show) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
            params.setMargins(0, 0, 0, llInder.getHeight());
            svLocation.setLayoutParams(params);
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getVideoBackEvent(VideoBackEvent videoBackEvent) {
        if (llMenu.getVisibility() == View.VISIBLE) {
            llMenu.setVisibility(View.GONE);
            return;
        }

        if (llInder.getVisibility() == View.VISIBLE) {
            llInder.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) svLocation.getLayoutParams();
            params.setMargins(0, 0, 0, 0);
            svLocation.setLayoutParams(params);
            return;
        }
        new AlertDialog.Builder(context)
                .setTitle(R.string.quit_hint)
                .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FaceCall.instance().terminateCurrentCall();
                        HangupEvent hangupEvent = new HangupEvent();
                        EventBus.getDefault().post(hangupEvent);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

}
